﻿Imports ADOEntityKYC
Imports System.Data
Partial Class Administrator_MOCCUPATION
    Inherits Web.UI.BasePage
    Dim mMasterEntity As KYCEntities
    Dim dsMaster As New DataSet
    Dim clsQuery As clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim strMsg As String = ""

#Region " Even Page "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        lblOCCCODE.Text = "รหัสอาชีพ"
        lblOCCNAME.Text = "ชื่ออาชีพ"
        lblOCCTYPE.Text = "ประเภทอาชีพ"
        lblRISK.Text = "ระดับความเสี่ยง"
        lblOCCSTATUS.Text = "สถานะการใช้ข้อมูล"
        rbtACTIVE.Text = "ใช้งาน"
        rbtINACTIVE.Text = "ไม่ใช้งาน"

        btnSearch.Text = Resources.resButton.btnSearch
        btnAdd.Text = Resources.resButton.btnAdd
        btnAddSub.Text = Resources.resButton.btnAddSub
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        btnClear.Text = Resources.resButton.btnClear
        btnPrint.Text = Resources.resButton.btnPrint

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        chkIsLogin()
        clsSessionMenuRight = Session("clsMenuRight")

        Dim popup_print = String.Format("OpenWindowWithPost('../Form/frmPrintRptMaster.aspx?rptType={0}','width=800,height=600,left=100,top=100,resizable=yes,scrollbars=yes');", _
                                        "209") ' -- รหัส rptType
        btnPrint.Attributes.Add("onclick", popup_print)

        If (Not IsPostBack) Then
            'IsDataBind()
            CreateControlMP()
            setButton(1)
            SetControl_Button()
        Else
            dsMaster = Session("dsTblMaster")
            grdMaster.DataSource = dsMaster.Tables("dsMaster")
            grdMaster.DataBind()
        End If
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsMaster
    End Sub

#End Region

#Region " SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "ข้อมูลหลัก > KYC > อาชีพ"
    End Sub

    Sub SetControl_Button()
        btnSearch.Attributes.Add("onclick", "NoDoubleSubmit();")
        btnModify.Attributes.Add("onclick", "NoDoubleSave();")
        btnAdd.Attributes.Add("onclick", "NoDoubleSave();")
        btnDelete.Attributes.Add("onclick", "NoDoubleSave();")
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLog(1)
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click

        Try
            If chkBeforeSave() Then
                mMasterEntity = New KYCEntities
                Dim sMaster As New MOCCUPATION

                sMaster.OCCCODE = txtOCCCODE.Text
                sMaster.OCCNAME = txtOCCNAME.Text
                sMaster.OCCTYPE = 0
                sMaster.RISK = txtRISK.Text
                sMaster.OCCSTATUS = If(rbtACTIVE.Checked, 1, 0)
                mMasterEntity.AddToMOCCUPATION(sMaster)
                mMasterEntity.SaveChanges()
                SaveLog(3)
                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)

            End If
        Catch ex As System.Data.UpdateException

            Dim codeError() As String = ex.InnerException.Message.Split(":")
            If codeError(0) = "ORA-00001" Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถเพิ่มได้ เนื่องจากรหัสนี้มีการนำมาใช้ในระบบแล้ว')", True)
            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)

        End Try
    End Sub

    Protected Sub btnAddSub_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddSub.Click
        Dim index As Integer = grdMaster.SelectedIndex
        Response.Redirect("MOCCUPATION_SUB.aspx?OCCCODE=" & grdMaster.Rows(index).Cells(1).Text & "")
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
        Try
            If chkBeforeSave() Then
                mMasterEntity = New KYCEntities
                Dim sMaster As New MOCCUPATION

                Dim row = (From m In mMasterEntity.MOCCUPATION Where m.OCCCODE = txtOCCCODE.Text).FirstOrDefault
                row.OCCCODE = txtOCCCODE.Text
                row.OCCNAME = txtOCCNAME.Text
                row.OCCTYPE = 0
                row.RISK = txtRISK.Text
                row.OCCSTATUS = If(rbtACTIVE.Checked, 1, 0)
                mMasterEntity.SaveChanges()
                SaveLog(4)
                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)
            End If

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)

        End Try


    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Not (grdMaster.SelectedIndex = -1) Then
            Dim DepC As String = grdMaster.Rows(grdMaster.SelectedIndex).Cells(1).Text
            Try
                mMasterEntity = New KYCEntities
                Dim qry = (From m In mMasterEntity.MOCCUPATION Where m.OCCCODE = DepC).ToList
                mMasterEntity.DeleteObject(qry(0))
                mMasterEntity.SaveChanges()
                SaveLog(5)
                IsDataBind()
                reset()

            Catch ex As System.Data.UpdateException
                Dim codeError() As String = ex.InnerException.Message.Split(":")
                If codeError(0) = "ORA-02292" Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                Else
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                End If

            Catch ex As Exception
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)

            End Try

        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If

    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        clear()
    End Sub

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        SaveLog(2)
    End Sub

#End Region

#Region " Even GridView"

    Protected Sub grdMaster_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdMaster.SelectedIndexChanged
        If (grdMaster.SelectedIndex = intBeforeItemIndex) Then
            clearGvIndex()
            reset()

            btnModify.Text = "แก้ไข"
        Else
            btnModify.Text = "บันทึก"

            setButton(2)

            txtOCCCODE.Text = grdMaster.Rows(grdMaster.SelectedIndex).Cells(1).Text
            txtOCCNAME.Text = grdMaster.Rows(grdMaster.SelectedIndex).Cells(2).Text
            txtOCCTYPE.Text = grdMaster.Rows(grdMaster.SelectedIndex).Cells(3).Text
            txtRISK.Text = grdMaster.Rows(grdMaster.SelectedIndex).Cells(4).Text
            If (CType(grdMaster.Rows(grdMaster.SelectedIndex).FindControl("grd_hid_OCCSTATUS"), HiddenField).Value) Then
                rbtACTIVE.Checked = True
            Else
                rbtINACTIVE.Checked = True
            End If

            btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                       IIf(grdMaster.SelectedIndex = -1, "", grdMaster.Rows(grdMaster.SelectedIndex).Cells(2).Text)) + "');")
        End If

    End Sub

    Protected Sub grdMaster_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdMaster.SelectedIndexChanging
        intBeforeItemIndex = grdMaster.SelectedIndex
    End Sub

    Protected Sub grdMaster_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdMaster.PageIndexChanging
        grdMaster.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub grdMaster_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdMaster.Sorting
        Dim dt = TryCast(dsMaster.Tables("dsMaster"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            grdMaster.DataSource = dsMaster.Tables("dsMaster")
            grdMaster.DataBind()
            clearGvIndex()
        End If
    End Sub

#End Region

#Region " Function"

    Private Sub clearGvIndex()
        grdMaster.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()

        mMasterEntity = New KYCEntities

        If dsMaster.Tables.Contains("dsMaster") Then
            dsMaster.Tables.Clear()
        End If
        Dim qry = From m In mMasterEntity.MOCCUPATION
                        Order By m.OCCCODE
                    Select m.OCCCODE, m.OCCNAME, m.OCCTYPE, m.OCCSTATUS, m.RISK

        If Not (txtOCCCODE.Text = "") Then
            If IsNumeric(txtOCCCODE.Text) = False Then
                strMsg = "กรุณาระบุรหัสเป็นตัวเลข" & "\n"
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)
                Exit Sub
            End If
            qry = qry.Where(Function(x) x.OCCCODE = txtOCCCODE.Text)
        End If

        If Not (txtOCCNAME.Text = "") Then
            qry = qry.Where(Function(x) x.OCCNAME.ToUpper.Contains(txtOCCNAME.Text.ToUpper))
        End If

        If Not (txtOCCTYPE.Text = "") Then
            qry = qry.Where(Function(x) x.OCCTYPE = txtOCCTYPE.Text)
        End If

        If Not (txtRISK.Text = "") Then
            qry = qry.Where(Function(x) x.RISK = txtRISK.Text)
        End If

        If rbtACTIVE.Checked Then
            qry = qry.Where(Function(x) x.OCCSTATUS = True)
        End If

        If rbtINACTIVE.Checked Then
            qry = qry.Where(Function(x) x.OCCSTATUS = False)
        End If

        dsMaster.Tables.Add(clsDataTable.LINQToDataTable(qry, "dsMaster").Copy)

        If (qry.Count = 0) Then
            lblMsg.Visible = True
            lblTotal.Text = ""
        Else
            lblMsg.Visible = False
            lblTotal.Text = "จำนวนรายการทั้งหมด " + qry.Count.ToString + " รายการ "

        End If

        grdMaster.DataSource = dsMaster.Tables("dsMaster")
        grdMaster.DataBind()

        clsDataTable = Nothing

    End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            lblMsg.Visible = False

            btnModify.Enabled = False
            btnDelete.Enabled = False
            btnAddSub.Enabled = False
            btnSearch.Enabled = True
            btnAdd.Enabled = True

            txtOCCCODE.Enabled = True

        ElseIf button = 2 Then 'select

            btnSearch.Enabled = False
            btnAdd.Enabled = False
            btnAddSub.Enabled = True
            btnModify.Enabled = True
            btnDelete.Enabled = True

            txtOCCCODE.Enabled = False

        End If

    End Sub

    Private Sub clear()

        If dsMaster.Tables.Contains("dsMaster") Then
            dsMaster.Tables("dsMaster").Clear()
            grdMaster.DataSource = dsMaster.Tables("dsMaster")
            grdMaster.DataBind()
        End If

        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtOCCCODE.Text = ""
        txtOCCNAME.Text = ""
        txtOCCTYPE.Text = ""
        txtRISK.Text = ""
        rbtACTIVE.Checked = False
        rbtINACTIVE.Checked = False
        btnModify.Text = "แก้ไข"
    End Sub

    Private Sub reset()
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtOCCCODE.Text = ""
        txtOCCNAME.Text = ""
        txtOCCTYPE.Text = ""
        txtRISK.Text = ""
        rbtACTIVE.Checked = False
        rbtINACTIVE.Checked = False
    End Sub

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True

        If (txtOCCCODE.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุรหัส" & "\n"
        Else
            If IsNumeric(txtOCCCODE.Text) = False Then
                result = False
                strMsg = strMsg & "กรุณาระบุรหัสเป็นตัวเลข" & "\n"
            End If
        End If

        If (txtOCCNAME.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุชื่อผลิตภัณฑ์" & "\n"
        End If

        If (txtOCCTYPE.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุประเภทอาชีพ" & "\n"
        End If

        If (txtRISK.Text = "") Then
            txtRISK.Text = "0"
            'result = False
            'strMsg = strMsg & "กรุณาระบุระดับความเสี่ยง" & "\n"
        End If

        If (rbtACTIVE.Checked = False And rbtINACTIVE.Checked = False) Then
            result = False
            strMsg = strMsg & "กรุณาระบุสถานะการใช้ข้อมูล" & "\n"
        End If

        Return result

    End Function

    Private Sub SaveLog(ByVal index As Integer)
        Try
            Dim program As String = "M71"
            Dim programName As String = " ข้อมูลหลัก > KYC > อาชีพ"

            Dim desc As String = ""
            If index = 1 Then
                desc = "ค้นหา" + programName
            ElseIf index = 2 Then
                desc = "พิมพ์" + programName
            ElseIf index = 3 Then
                desc = "บันทึก" + programName + " (รหัสอาชีพ " + txtOCCCODE.Text + ")"
            ElseIf index = 4 Then
                desc = "บันทึก แก้ไข" + programName + " (รหัสอาชีพ " + txtOCCCODE.Text + ")"
            ElseIf index = 5 Then
                desc = "ลบ" + programName + " (รหัสอาชีพ " + txtOCCCODE.Text + ")"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtOCCCODE.Text.Trim, clsSessionMenuRight.getUserName, index, desc, program)


            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

End Class
